package com.hspedu.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/3/2
 * @time 23:23
 */
public class UDPReceiverA {
    public static void main(String[] args) throws IOException {
        //在9999端口等待接收数据
        DatagramSocket datagramSocket = new DatagramSocket(9999);

        //创建一个数据报对象，准备接受数据
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        //调用接收方法，将通过网络传输的datagramPacket对象填充到packet
        datagramSocket.receive(packet);

        //将packet拆包，取出数据并显示
        //取出数据报的实际长度
        int length = packet.getLength();
        byte[] data = packet.getData();
        String s = new String(data, 0, length);
        System.out.println(s);

        byte[] bytes = "好的，明天见！".getBytes();
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length,InetAddress.getLocalHost(),9998);
        datagramSocket.send(datagramPacket);
    }
}
